//
//  VoiceRecord.m
//  YiqiMobile
//
//  Created by henry on 13-3-30.
//  Copyright (c) 2013年 henry. All rights reserved.
//

#import "VoiceRecord.h"


@implementation VoiceRecord


- (id)init{
    self = [super init];
    if (self) {
        // Custom initialization
        AVAudioSession *session = [AVAudioSession sharedInstance];
        NSError *sessionError;
        [session setCategory:AVAudioSessionCategoryPlayAndRecord error:&sessionError];
       // _sampleRate  = 44100;
        _sampleRate  = 20000;
        _quality     = AVAudioQualityLow;
        _formatIndex = kAudioFormatLinearPCM;
        _recording = _playing = _hasCAFFile = NO;
        if(session == nil)
            NSLog(@"Error creating session: %@", [sessionError description]);
        else
            [session setActive:YES error:nil];
    }
    return self;
}

- (IBAction) recordBtnClick:(NSString*) antoplay
{
    if (!_recording){
        NSDictionary *settings = [NSDictionary dictionaryWithObjectsAndKeys:
                                  [NSNumber numberWithFloat: _sampleRate],                  AVSampleRateKey,
                                  [NSNumber numberWithInt: _formatIndex],                   AVFormatIDKey,
                                  [NSNumber numberWithInt: 2],                              AVNumberOfChannelsKey,
                                  [NSNumber numberWithInt: _quality],                       AVEncoderAudioQualityKey,
                                  nil];
        
        _recordedFile = [NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingString:@"RecordedFile"]];
        NSError* error;
        _recorder = [[AVAudioRecorder alloc] initWithURL:_recordedFile settings:settings error:&error];
        if (error)
        {
            UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"Sorry"
                                                            message:@"your device doesn't support your setting"
                                                           delegate:self
                                                  cancelButtonTitle:@"OK"
                                                  otherButtonTitles: nil];
            [alert show];
            return;
        }
        _recording = YES;
        [_recorder prepareToRecord];
        _recorder.meteringEnabled = YES;
        [_recorder record];
        
        _timer = [NSTimer scheduledTimerWithTimeInterval:.01f
                                                  target:self
                                                selector:@selector(timerUpdate)
                                                userInfo:nil
                                                 repeats:YES];
        //[_recordBtn setTitle:@"Stop Record" forState:UIControlStateNormal];
    }
    else
    {
        //[_recordBtn setTitle:@"Start Record" forState:UIControlStateNormal];
        _recording = NO;
        
        [_timer invalidate];
        _timer = nil;
        
        if (_recorder != nil )
        {
            _hasCAFFile = YES;
            //_playBtn.enabled = YES;
        }
        [_recorder stop];
        _recorder = nil;
        [ self encodeBtnClick:antoplay];
    }
}


//转换mp3格式
- (IBAction) encodeBtnClick:(NSString*) antoplay{
    if (_hasCAFFile && !_recording && !_playing)
    {
        [[UIApplication sharedApplication] beginIgnoringInteractionEvents];
        _startDate = [NSDate date];
        [NSThread detachNewThreadSelector:@selector(toMp3:) toTarget:self withObject:antoplay];
    }
}

- (void) toMp3:(NSString*) antoplay{
    [self  outputSgtClick:1];
    NSString *cafFilePath =[NSTemporaryDirectory() stringByAppendingString:@"RecordedFile"];
    
    NSString *mp3FileName = @"Mp3File";
    mp3FileName = [mp3FileName stringByAppendingString:@".mp3"];
    NSString *mp3FilePath = [[NSHomeDirectory() stringByAppendingFormat:@"/Documents/"] stringByAppendingPathComponent:mp3FileName];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:mp3FilePath]){
        NSError *error;
        if ([fileManager removeItemAtPath:mp3FilePath error:&error]) {
            NSLog(@"%@",@"删除语音文件");
        }
        
    }
    @try {
        int read, write;
        
        FILE *pcm = fopen([cafFilePath cStringUsingEncoding:1], "rb");  //source
        fseek(pcm, 4*1024, SEEK_CUR);                                   //skip file header
        FILE *mp3 = fopen([mp3FilePath cStringUsingEncoding:1], "wb");  //output
        
        const int PCM_SIZE = 8192;
        const int MP3_SIZE = 8192;
        short int pcm_buffer[PCM_SIZE*2];
        unsigned char mp3_buffer[MP3_SIZE];
        
        lame_t lame = lame_init();
        lame_set_in_samplerate(lame, _sampleRate);
        lame_set_VBR(lame, vbr_default);
        lame_init_params(lame);
        
        do {
            read = fread(pcm_buffer, 2*sizeof(short int), PCM_SIZE, pcm);
            if (read == 0)
                write = lame_encode_flush(lame, mp3_buffer, MP3_SIZE);
            else
                write = lame_encode_buffer_interleaved(lame, pcm_buffer, read, mp3_buffer, MP3_SIZE);
            
            fwrite(mp3_buffer, write, 1, mp3);
            
        } while (read != 0);
        
        lame_close(lame);
        fclose(mp3);
        fclose(pcm);
    }
    @catch (NSException *exception) {
        NSLog(@"%@",[exception description]);
    }
    @finally {
        [self performSelectorOnMainThread:@selector(convertMp3Finish:)
                               withObject:antoplay
                            waitUntilDone:YES];
    }
}

- (void) convertMp3Finish:(NSString*) antoplay{    
    _hasMp3File = YES;
    [[UIApplication sharedApplication] endIgnoringInteractionEvents];
    NSString *fileUrl=[NSHomeDirectory() stringByAppendingFormat:@"/Documents/%@", @"Mp3File.mp3"];
    NSInteger fileSize =  [self getFileSize:fileUrl];
    
      NSLog(@"%@,fileSize=%dkb",@" convert fuccess",fileSize/1024);
    if (self.delegate&&[_delegate respondsToSelector:@selector(convertTomp3Success:)]) {
        [self.delegate  convertTomp3Success:fileUrl];
    }
    [self playMp3BtnClick:antoplay];
  
   
}
- (IBAction) outputSgtClick:(int) tag
{
    if (tag==0)//听筒
    {
        UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_None;
        AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute,sizeof (audioRouteOverride),&audioRouteOverride);
    }
    else
    {//扬声器
        UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
        AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute,sizeof (audioRouteOverride),&audioRouteOverride);
    }
}


- (IBAction) playMp3BtnClick:(NSString*) antoplay
{
    if ([antoplay isEqualToString:@"0"]) {
        return;
    }
    if (_recording || _playing || !_hasMp3File || !_hasCAFFile){
        return;
    }
    NSString *fileUrl=[NSHomeDirectory() stringByAppendingFormat:@"/Documents/%@", @"Mp3File.mp3"];
    [self playMp3Click:fileUrl];
}
- (void) playMp3Click:(NSString*) fileUrl{
    if (_playingMp3){
        [_timer invalidate];
        _playingMp3 = NO;
        [_mp3Player pause];
    }else{
        if (_mp3Player == nil){
            NSURL *url=[NSURL URLWithString:fileUrl];
            NSError *playerError;
            _mp3Player = [[AVAudioPlayer alloc] initWithContentsOfURL:url
                                                                error:&playerError];
            //_mp3Player = [[AVAudioPlayer alloc] initWithData:[NSData dataWithContentsOfURL:url] error:&playerError];
            _mp3Player.volume=0.9f;
            _mp3Player.meteringEnabled = YES;
            if (_mp3Player == nil){
               // [self playMyVedio:url];
                NSLog(@"ERror creating player: %@", [playerError description]);
            }
            _mp3Player.delegate = self;
        }
        _playingMp3 = YES;
        if (![_mp3Player play]) {
            NSLog(@"%@",@"AVAudioPlayer不能播放此文件");
        };
        _timer = [NSTimer scheduledTimerWithTimeInterval:.1
                                                  target:self
                                                selector:@selector(timerUpdate)
                                                userInfo:nil
                                                 repeats:YES];
    }
}



- (void) timerUpdate
{
    if (_recording)
    {
        int m = _recorder.currentTime / 60;
        int s = ((int) _recorder.currentTime) % 60;
        int ss = (_recorder.currentTime - ((int) _recorder.currentTime)) * 100;
        
        _duration = [NSString stringWithFormat:@"%.2d:%.2d %.2d", m, s, ss];
        // _duration = [NSString stringWithFormat:@"%.2d:%.2d", m, s];
        _fileSize =  [self getFileSize:[NSTemporaryDirectory() stringByAppendingString:@"RecordedFile"]]/1024;

    }
}

- (NSInteger) getFileSize:(NSString*) path{
    NSFileManager * filemanager = [[NSFileManager alloc]init];
    if([filemanager fileExistsAtPath:path]){
        NSDictionary * attributes = [filemanager attributesOfItemAtPath:path error:nil];
        NSNumber *theFileSize;
        if ( (theFileSize = [attributes objectForKey:NSFileSize]) )
            return  [theFileSize intValue];
        else
            return -1;
    }
    else
    {
        return -1;
    }
}



#pragma mark - AVAudioPlayerDelegate
- (void) audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
    if (_mp3Player == player)
    {
        //[_playMp3Btn setTitle:@"MP3Play" forState:UIControlStateNormal];
        [_timer invalidate];
        _timer = nil;
        _playingMp3 = NO;
    }
    else
    {
        //[_playBtn setTitle:@"CAFPlay" forState:UIControlStateNormal];
        [_timer invalidate];
        _timer = nil;
        _playing = NO;
    }
}


@end
